
#ifndef __json_pref_store_h__
#define __json_pref_store_h__

#pragma once

#include <string>

#include "base/basic_types.h"
#include "base/file_path.h"
#include "base/memory/scoped_ptr.h"
#include "base/observer_list.h"

#include "important_file_writer.h"
#include "persistent_pref_store.h"

namespace base
{
    class DictionaryValue;
    class MessageLoopProxy;
    class Value;
}

class FilePath;

// A writable PrefStore implementation that is used for user preferences.
class JsonPrefStore : public PersistentPrefStore,
    public ImportantFileWriter::DataSerializer
{
public:
    // |file_message_loop_proxy| is the MessageLoopProxy for a thread on which
    // file I/O can be done.
    JsonPrefStore(const FilePath& pref_filename,
        base::MessageLoopProxy* file_message_loop_proxy);
    virtual ~JsonPrefStore();

    // PrefStore overrides:
    virtual ReadResult GetValue(const std::string& key,
        const base::Value** result) const;
    virtual void AddObserver(PrefStore::Observer* observer);
    virtual void RemoveObserver(PrefStore::Observer* observer);
    virtual bool IsInitializationComplete() const;

    // PersistentPrefStore overrides:
    virtual ReadResult GetMutableValue(const std::string& key,
        base::Value** result);
    virtual void SetValue(const std::string& key, base::Value* value);
    virtual void SetValueSilently(const std::string& key, base::Value* value);
    virtual void RemoveValue(const std::string& key);
    virtual bool ReadOnly() const;
    virtual PrefReadError ReadPrefs();
    virtual void ReadPrefsAsync(ReadErrorDelegate* error_delegate);
    virtual bool WritePrefs();
    virtual void ScheduleWritePrefs();
    virtual void CommitPendingWrite();
    virtual void ReportValueChanged(const std::string& key);

    // This method is called after JSON file has been read. Method takes
    // ownership of the |value| pointer. Note, this method is used with
    // asynchronous file reading, so class exposes it only for the internal needs.
    // (read: do not call it manually).
    void OnFileRead(base::Value* value_owned, PrefReadError error, bool no_dir);

private:
    // ImportantFileWriter::DataSerializer overrides:
    virtual bool SerializeData(std::string* output);

    FilePath path_;
    scoped_refptr<base::MessageLoopProxy> file_message_loop_proxy_;

    scoped_ptr<base::DictionaryValue> prefs_;

    bool read_only_;

    // Helper for safely writing pref data.
    ImportantFileWriter writer_;

    ObserverList<PrefStore::Observer, true> observers_;

    scoped_ptr<ReadErrorDelegate> error_delegate_;

    bool initialized_;

    DISALLOW_COPY_AND_ASSIGN(JsonPrefStore);
};

#endif //__json_pref_store_h__